#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket短连接报文收发.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/12/29 13:13 
"""

import socket
from queue import Queue


def short_connection_sender(host, port, message_queue):
	with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
		s.connect((host, port))
		while not message_queue.empty():
			message = message_queue.get()
			s.sendall(message.encode())
			print(f"发送：{message}")
	print("发送队列空，关闭连接。")


# 接收报文（短连接）
def short_connection_receiver(host, port):
	with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
		s.bind((host, port))
		s.listen()
		conn, addr = s.accept()
		with conn:
			print(f"连接地址：{addr}")
			while True:
				data = conn.recv(1024)
				if not data:
					break
				print(f"接收：{data.decode()}")
	print("连接关闭。")
